import React, { useState, useEffect } from 'react'
import { fetchCates, fetchItems } from '@a/index'
import MyTabbar from '@c/MyTabbar'
import './style.scss'
import Icon from '@c/Icon'
import { useNavigate } from 'umi'
export default function index() {
  const navigate = useNavigate();
  // 所有分类
  const [cates, setCates] = useState<any[]>([]);
  // 高亮分类对应商品列表
  const [items, setItems] = useState<any[]>([]);
  // 控制 分类高亮的下标
  const [activeIndex, setActiveIndex] = useState<number>(0);
  // 切换高亮分类
  const switchActive = (index: number) => {
    setActiveIndex(index)
  }
  // 请求分类数据
  const getCates = () => {
    fetchCates().then(res => {
      if (res.data.code === 0) {
        setCates(res.data.data)
      }
    })
  }
  // 请求高亮 分类下商品列表
  const getItems = () => {
    fetchItems({
      categoryId: cates[activeIndex].id
    }).then(res => {
      if (res.data.code === 0) {
        setItems(res.data.data.result)
      }
      if (res.data.code === 700) {
        setItems([])
      }
    })
  }
  useEffect(() => {
    // 跳过初始化
    if (cates.length !==0) {
      getItems();
    }
    
  }, [cates, activeIndex])
  useEffect(() => {
    getCates();
  }, [])
  return (
    <div className='cate-contaienr'>
      <div className="container">
        <div className="cate-wrap">
          <div className="cates">
            {
              cates.map((cate, index) => (
                <div 
                  className={`cate ${activeIndex=== index? 'active': ''}`}
                  onClick={
                    () => {
                      switchActive(index)
                    }
                  }
                  key={cate.id}
                >
                  {cate.name}
                </div>
              ))
            }
          </div>
        </div>
        <div className="item-wrap">
        <div className="items">
            {
              items.map(item => (
                <div 
                  className="item" 
                  onClick={
                    () => {
                      navigate(`/detail/${item.id}`)
                    }
                  }
                  key={item.id}>
                  <img src={item.pic} alt="" className="item-img" />
                  <div className="item-info">
                    <h5 className="item-name">{item.name}</h5>
                    <div className="item-action">
                      <p className="price">￥{item.minPrice}</p>
                      <Icon name="gouwuchetianjia" color="#e93323" size={24} />
                    </div>
                  </div>
                </div>
              ))
            }

          </div>
        </div>
      </div>
      <MyTabbar/>
    </div>
  )
}
